package com.tangkun.environment.fragment.home;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tangkun.environment.R;
import com.tangkun.environment.activity.ErWeiMaActivity;
import com.tangkun.environment.activity.TiJiaoXunChaShuJuActivity;
import com.tangkun.environment.adapter.XunChaShuJuAdapter;
import com.tangkun.environment.entity.shouye.EnterpriseViewReturn;
import com.tangkun.environment.entity.shouye.InspectflowIndexReturn;
import com.tangkun.environment.fragment.BaseFragment;
import com.tangkun.environment.network.GlobalUrl;
import com.tangkun.environment.network.MySubscribe;
import com.tangkun.environment.rx.RxFragmentHelper;
import com.tangkun.environment.utils.JumpHelper;
import com.tangkun.environment.utils.Utils;
import com.tangkun.environment.view.CircleImageView;
import com.tangkun.environment.view.CommonQueDingDialog;
import com.tangkun.environment.view.CustomListView;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

/**
 * 巡查数据Fragment
 */

public class XunChaShuJuFragment extends BaseFragment implements XunChaShuJuAdapter.MyClickListener {

    @BindView(R.id.tv_jichushuju_tips)
    TextView tvJichushujuTips;
    @BindView(R.id.iv_jichushuju_tips)
    ImageView ivJichushujuTips;
    @BindView(R.id.ll_jichushuju_tips)
    LinearLayout llJichushujuTips;
    @BindView(R.id.civ_jichushuju_photo)
    CircleImageView civJichushujuPhoto;
    @BindView(R.id.iv_jichushuju_yichang)
    ImageView ivJichushujuYichang;
    @BindView(R.id.tv_jichushuju_name)
    TextView tvJichushujuName;
    @BindView(R.id.tv_jichushuju_dingwei)
    TextView tvJichushujuDingwei;
    @BindView(R.id.tv_jichushuju_erweima)
    ImageView tvJichushujuErweima;
    @BindView(R.id.custom_list_view)
    CustomListView customListView;
    @BindView(R.id.tv_jichushuju_rili)
    TextView tvJichushujuRili;
    @BindView(R.id.iv_jichushuju_rili)
    ImageView ivJichushujuRili;
    private Context mContext;

    /**
     * 企业ID
     */
    private String id = "";

    /**
     * 数据源
     */
    private List<InspectflowIndexReturn.DataBean.FlowlistBean> dataList = new ArrayList<InspectflowIndexReturn.DataBean.FlowlistBean>();
    /**
     * 适配器
     */
    private XunChaShuJuAdapter adapter;
    /**
     * 日期选择器
     */
    private DatePicker datePicker;
    /**
     * 年
     */
    private String currentYear = Utils.getCurrentDateYear();
    /**
     * 月
     */
    private String currentMonth = Utils.getCurrentDateMonth();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_xunchashuju, container, false);
        ButterKnife.bind(this, view);
        id = getArguments().getString("id");
        EventBus.getDefault().register(this);
        mContext = getActivity();
        initView();
        initData();
        return view;
    }

    private void initView() {
        adapter = new XunChaShuJuAdapter(mContext, dataList);
        adapter.setMyClickListener(this);
        customListView.setAdapter(adapter);
    }

    private void initData() {
        enterpriseView();
        inspectflowIndex();
    }

    /**
     * 企业中心
     */
    private void enterpriseView() {
        fromNetwork.enterpriseView(id).compose(new RxFragmentHelper<EnterpriseViewReturn>().ioMain(getActivity(), XunChaShuJuFragment.this, true))
                .subscribe(new MySubscribe<EnterpriseViewReturn>(getActivity(), true) {
                    @Override
                    protected void success(EnterpriseViewReturn resultBean) {
                        if (resultBean.data != null) {
                            //顶部小黄条
                            if (resultBean.data.errornum > 0) {
                                tvJichushujuTips.setText("检测企业" + resultBean.data.errornum + "组基础数据异常，请修改、补充、完善。");
                                llJichushujuTips.setVisibility(View.VISIBLE);
                            } else {
                                llJichushujuTips.setVisibility(View.GONE);
                            }
                            //头像
                            Glide.with(getActivity())
                                    .load(GlobalUrl.IMG_URL + resultBean.data.img)
                                    .bitmapTransform(new CropCircleTransformation(getActivity()))
                                    .placeholder(R.mipmap.ic_guanlianqiye_shangchuandianzhao)
                                    .dontAnimate()
                                    .into(civJichushujuPhoto);
                            //店铺名字
                            if (!TextUtils.isEmpty(resultBean.data.name)) {
                                tvJichushujuName.setText(resultBean.data.name);
                            } else {
                                tvJichushujuName.setText("");
                            }
                            //定位
                            if (!TextUtils.isEmpty(resultBean.data.address)) {
                                tvJichushujuDingwei.setText(resultBean.data.address);
                            } else {
                                tvJichushujuDingwei.setText("");
                            }
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage + "");
                    }
                });
    }

    /**
     * 巡查数据列表
     */
    private void inspectflowIndex() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("date", Utils.getLastDayOfMonth(Integer.valueOf(currentYear), Integer.valueOf(currentMonth)));//选中月份最后一天
        map.put("enterpriseid", id);
        fromNetwork.inspectflowIndex(map).compose(new RxFragmentHelper<InspectflowIndexReturn>().ioMain(getActivity(), XunChaShuJuFragment.this, true))
                .subscribe(new MySubscribe<InspectflowIndexReturn>(getActivity(), true) {
                    @Override
                    protected void success(InspectflowIndexReturn resultBean) {
                        dataList.clear();
                        if (resultBean.data != null) {
                            for (int i = 0; i < resultBean.data.size(); i++) {
                                if (resultBean.data.get(i).flowlist != null) {
                                    for (int j = 0; j < resultBean.data.get(i).flowlist.size(); j++) {
                                        if (j == 0) {//第一步 提交
                                            //标记第一步
                                            resultBean.data.get(i).flowlist.get(j).isFirstStep = true;
                                            dataList.add(resultBean.data.get(i).flowlist.get(j));
                                        } else if (j == resultBean.data.get(i).flowlist.size() - 1) {
                                            //标记最后一步
                                            resultBean.data.get(i).flowlist.get(j).isLastStep = true;
                                            dataList.add(resultBean.data.get(i).flowlist.get(j));
                                        } else {
                                            //标记非第一步
                                            resultBean.data.get(i).flowlist.get(j).isFirstStep = false;
                                            //标记非最后一步
                                            resultBean.data.get(i).flowlist.get(j).isLastStep = false;
                                            dataList.add(resultBean.data.get(i).flowlist.get(j));
                                        }
                                    }
                                    //设置标题 赋值过标题后就不要再赋值标题了 切换日期时要将标题置空
                                    if (!TextUtils.isEmpty(resultBean.data.get(i).title)) {
                                        tvJichushujuRili.setText(resultBean.data.get(i).title);
                                    } else {
                                        tvJichushujuRili.setText("");
                                    }
                                }
                            }

                            //没有数据
                            if (resultBean.data.size() == 0) {
                                tvJichushujuRili.setText(currentMonth + "月暂无巡查数据");
                            }

                            adapter.setJiedianPosion(-1);
                            adapter.notifyDataSetChanged();
                        } else {
                            adapter.setJiedianPosion(-1);
                            adapter.notifyDataSetChanged();
                            tvJichushujuRili.setText(currentMonth + "月暂无巡查数据");
                        }
                    }

                    @Override
                    protected void onMyError(String errorMessage) {
                        showToast(errorMessage + "");
                    }
                });
    }

    @OnClick({R.id.iv_jichushuju_tips, R.id.tv_jichushuju_erweima, R.id.iv_jichushuju_rili})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_jichushuju_tips://隐藏顶部小黄条
                llJichushujuTips.setVisibility(View.GONE);
                break;
            case R.id.tv_jichushuju_erweima://二维码
                Intent erweimaIntent = new Intent(getActivity(), ErWeiMaActivity.class);
                erweimaIntent.putExtra("id", id);
                JumpHelper.jump(getActivity(), erweimaIntent, false);
                break;
            case R.id.iv_jichushuju_rili://选择月份
                if (datePicker != null && datePicker.isShowing()) {
                    datePicker.dismiss();
                } else {
                    datePicker = new DatePicker(getActivity(), 1);
                    //顶部高度
                    datePicker.setTopHeight(47);
                    //取消按钮颜色
                    datePicker.setCancelTextColor(getResources().getColor(R.color.common_tips));
                    //取消按钮文字大小
                    datePicker.setCancelTextSize(17);
                    //确认按钮颜色
                    datePicker.setSubmitTextColor(getResources().getColor(R.color.common_green));
                    //按下的文字颜色
                    datePicker.setPressedTextColor(getResources().getColor(R.color.common_green_80));
                    //确认按钮文字大小
                    datePicker.setSubmitTextSize(17);
                    //顶部标题栏下划线颜色
                    datePicker.setTopLineColor(getResources().getColor(R.color.divider_color_80));
                    //顶部标题栏下划线高度
                    datePicker.setTopLineHeight(1);
                    //日期上下分割线颜色
                    datePicker.setLineColor(getResources().getColor(R.color.common_word));
                    //日期颜色
                    datePicker.setTextColor(getResources().getColor(R.color.common_word));
                    //控件展示动画
                    datePicker.setAnimationStyle(R.style.PopupwindowStyle);
                    //年份范围
                    datePicker.setRange(1900, 2100);
                    //默认选择日期
                    datePicker.setSelectedItem(Integer.valueOf(currentYear), Integer.valueOf(currentMonth));
                    datePicker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {

                        @Override
                        public void onDatePicked(String year, String month) {
                            //赋值年月
                            currentYear = year;
                            currentMonth = month;
                            //清空巡查数据列表的标题
                            tvJichushujuRili.setText("");
                            //请求数据
                            inspectflowIndex();
                        }
                    });
                    datePicker.show();
                }
                break;
        }
    }

    //警示按钮监听事件
    @Override
    public void onStatusClick(int position) {
        String content = dataList.get(position).description;
        if (TextUtils.isEmpty(content)) {
            content = "暂无处理意见";
        }
        final CommonQueDingDialog commonQueDingDialog = new CommonQueDingDialog(getActivity(), "处理意见", content, "确定");
        commonQueDingDialog.show();
        commonQueDingDialog.setOnClickListener(new CommonQueDingDialog.OnClickListener() {
            @Override
            public void rightClick() {
                commonQueDingDialog.dismiss();
            }
        });
    }

    /**
     * 按钮监听事件
     *
     * @param type     0：查看数据 1：编辑数据 2：提交数据 3:审核
     * @param position 索引
     */
    @Override
    public void onBtnClick(int type, final int position) {
        Intent intent;
        switch (type) {
            case 0://查看数据
                intent = new Intent(getActivity(), TiJiaoXunChaShuJuActivity.class);
                intent.putExtra("id", dataList.get(position).enterpriseid);
                intent.putExtra("inspectid", dataList.get(position).inspectid);
                intent.putExtra("type", type);
                JumpHelper.jump(getActivity(), intent, false);
                break;
            case 1://编辑数据
                intent = new Intent(getActivity(), TiJiaoXunChaShuJuActivity.class);
                intent.putExtra("id", dataList.get(position).enterpriseid);
                intent.putExtra("inspectid", dataList.get(position).inspectid);
                intent.putExtra("type", type);
                JumpHelper.jump(getActivity(), intent, false);
                break;
            case 2://提交数据
                intent = new Intent(getActivity(), TiJiaoXunChaShuJuActivity.class);
                intent.putExtra("id", dataList.get(position).enterpriseid);
                intent.putExtra("inspectid", dataList.get(position).inspectid);
                intent.putExtra("type", type);
                JumpHelper.jump(getActivity(), intent, false);
                break;
            case 3://审核
                intent = new Intent(getActivity(), TiJiaoXunChaShuJuActivity.class);
                intent.putExtra("id", dataList.get(position).enterpriseid);
                intent.putExtra("inspectid", dataList.get(position).inspectid);
                intent.putExtra("shenheIds", dataList.get(position).ids);
                intent.putExtra("type", type);
                JumpHelper.jump(getActivity(), intent, false);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //修改企业资料成功刷新
    @Subscriber(tag = "QiYeZhongXinActivity.refresh")
    private void refresh(boolean b) {
        enterpriseView();
        inspectflowIndex();
    }
}